<template>
  <div class="search">
    <!-- 顶部搜素框 -->
    <form action="/" class="searchForm">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="onFocus"
        @blur="onBlur"
      />
    </form>

    <!-- 搜索历史 -->
    <search-his
      v-show="flag === 1"
      :searchHisList="searchHisList"
      @clear="searchHisList = []"
      @search="onSearch"
    />
    <!-- 搜索建议 -->
    <search-sug
      :searchText="searchText"
      v-show="flag === 2"
      @search="onSearch"
    />
    <!-- 搜索结果 -->
    <search-res
      v-show="flag === 3"
      :searchText="searchText"
      :isSearch="isSearch"
    />
  </div>
</template>

<script>
import searchHis from './components/searchHis'
import searchSug from './components/searchSug'
import searchRes from './components/searchRes'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'searchIndex',
  data () {
    return {
      searchText: '',
      isSearch: false,
      searchHisList: getItem('SearchHistory') || []
    }
  },
  components: {
    searchHis,
    searchSug,
    searchRes
  },
  computed: {
    flag () {
      if (!this.searchText) {
        return 1
      } else {
        if (!this.isSearch) {
          return 2
        } else {
          return 3
        }
      }
    }
  },
  created () {},
  watch: {
    searchHisList (val) {
      setItem('SearchHistory', val)
    }
  },
  methods: {
    onSearch (val) {
      this.isSearch = true
      this.searchText = val
      const index = this.searchHisList.indexOf(val)
      if (index !== -1) {
        this.searchHisList.splice(index, 1)
      }
      this.searchHisList.unshift(val)
    },
    onCancel () {
      this.$router.back()
    },
    onFocus () {
      this.isSearch = false
    },
    onBlur () {}
  }
}
</script>

<style scoped lang="less">
.van-search__action {
  color: #fff;
}
.searchForm {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 111;
}
.search {
  padding-top: 108px;
}
</style>
